var CryptoJS = require('../utils/aes.js');
const app = getApp(); //获取应用实例
///////////////////////////////////////////////////////////////////////////////
const user = wx.getStorageSync('userInfo')
//   let cookie = wx.getStorageSync('session_id');
//  var  header = {
//     "Content-Type": "application/x-www-form-urlencoded",
//     "Cookie": 'JSESSIONID=' + cookie + "; Path=/webapi; HttpOnly"
//   }


function getDataRequest(urlPath, requedata, successCallBack, failCallBack,server,isUncode) {
  var that = this
  var url = ''
  let bool = isUncode
  let isJson = false
  switch (server){
    case 'hotel':
      url = app.globalData.hotel_url + urlPath
      break;
    case 'seedoding':
      url = app.globalData.seeing_url + urlPath
      break;
    case 'javaHotel':
      url = app.globalData.java_url + urlPath
      isJson = true
      // bool = true
      break;
  }
  let hotel_token = wx.getStorageSync('access_token');
  if (!hotel_token) {
    var header = {
      // "Content-Type": "application/x-www-form-urlencoded",
      "Content-Type": isJson ? "application/json" :'application/x-www-form-urlencoded',
    }
  } else {
    var header = {
      Authorization: 'Bearer ' + hotel_token,
      "Content-Type": isJson ? "application/json" : 'application/x-www-form-urlencoded',
      // "token": 'JSESSIONID=' + cookie + "; Path=/webapi; HttpOnly"
    }
  }
  let params = ''
  if (bool) {
    params = Encrypt(requedata)
  } else {
    params = requedata

  }
  wx.request({
    url: url,
    method: 'post',
    data: params,
    header: header,
    success: function(res) {
      if (bool) {
        successCallBack(JSON.parse(decrypt(res.data)))
      } else {
        successCallBack(res.data)
      }
    },
    fail: function(res) {
      failCallBack(res);
    }
  })
}


const key = CryptoJS.enc.Utf8.parse("9876543211234567"); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('9876543211234567'); //十六位十六进制数作为密钥偏移量

function decrypt(word) {
  let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

/***
 * 加密
 */
function Encrypt(word) {
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString().toUpperCase();
}


function login(callback, filed, a, b) {
  var that = this;
  wx.login({
    success: res => {

      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      var code = res.code;
      var appId = app.globalData.appid;
      var url = app.globalData.url;
      // console.log(code)
      // console.log(appId)
      // console.log(url)
      //前台获取微信信息

      //用code换取sessionid

      wx.request({
        url: url + '/pub/jjr/wechatlogin',
        data: {
          code: code,
          appid: appId,
          isbinding: 1,
          mphone: a,
          mpassword: b
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success(res) {
          console.log(res)
          console.log("我是返回")
          if (res.data.flg == 1) {
            //需添加请求
            wx.setStorageSync('session_id', res.data.obj.sessionId);

            var cookie = wx.getStorageSync('session_id');
            console.log(cookie)

            console.log("我要开始请求了")
            wx.getUserInfo({
              success: function(e) {
                console.log(e)

                var avatarUrl = e.userInfo.avatarUrl
                var issex = ''
                console.log(avatarUrl)
                if (e.userInfo.gender == 0) {
                  issex = '4_3'
                }
                if (e.userInfo.gender == 1) {
                  issex = '4_1'
                }
                if (e.userInfo.gender == 2) {
                  issex = '4_2'
                }


                console.log(cookie)
                wx.request({
                  url: url + '/pri/userInfo',
                  data: {
                    nickname: e.userInfo.nickName,
                    avatarimg: e.userInfo.avatarUrl,
                    sex: issex,

                  },
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Cookie": 'JSESSIONID=' + cookie + "; Path=/webapi; HttpOnly"
                  },
                  method: "POST",
                  success(ms) {
                    console.log(ms)
                    wx.setStorage({
                      key: 'userInfo',
                      data: e.userInfo,
                      success: function(res) {
                        console.log("存储成功")
                      }
                    })
                    callback(res)
                  }
                })


              }
            })

          } else {
            filed(res)
          }
        }
      });


    }
  })
}

function uploadimg(imageurls, callback) {
  var pics = [];
  for (var i = 0; i < imageurls.length; i++) {
    var dict = imageurls[i];
    var srcurl = dict.src;
    var subsrcurl = dict.src;
    var headerUrl = app.globalData.Img;
    if ((srcurl.substring(0, 4) == 'http' || srcurl.substring(0, 6) == 'wxfile') && subsrcurl.substring(0, headerUrl.length) != headerUrl) {
      pics.push(dict.src)
    }
  }
  if (pics.length == 0) {
    callback([])
    return;
  }
  var data = {
    path: pics, //这里是选取的图片的地址数组
    i: 0,
    success: 0,
    fail: 0,
    getImageurl: [] //这里是服务器返回图片url的存放数组
  }
  imageOfUpload(data, callback)
}

function imageOfUpload(data, completecallBack) {
  console.log(data)
  wx.showLoading()
  //(i)当前上传的哪张图片
  var i = data.i; //当前上传的哪张图片
  var success = data.success; //上传成功的个数
  var fail = data.fail; //上传失败的个数
  var images = data.getImageurl;
  wx.uploadFile({
    url: app.globalData.Img + '/pri/jjr/houseold/save',
    filePath: data.path[i],
    name: 'file0', //这里根据自己的实际情况改
    success: (resp) => {
      // images.push(resp.data);
      // var jsonObj = JSON.parse(resp.data);
      console.log(resp)
      // if (jsonObj.status) {
      //   images.push(jsonObj.data);
      //   success++; //图片上传成功，图片上传成功的变量+1
      // }
    },
    fail: (res) => {
      fail++; //图片上传失败，图片上传失败的变量+1
    },
    complete: () => {
      wx.hideLoading();
      i++; //这个图片执行完上传后，开始上传下一张
      if (i == data.path.length) { //当图片传完时，停止调用   
        completecallBack(images)
      } else { //若图片还没有传完，则继续调用函数
        data.i = i;
        data.success = success;
        data.fail = fail;
        data.getImageurl = images;
        imageOfUpload(data, completecallBack);
      }
    }
  });
}

function getDates(days, todate) {
  var dateArry = [];
  for (var i = 0; i < days; i++) {
    var dateObj = dateLater(todate, i);
    dateArry.push(dateObj)
  }
  return dateArry;
}

function dateLater(dates, later) {
  let dateObj = {};
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate() + later);
  let day = date.getDay();
  let yearDate = date.getFullYear();
  let month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  let dayFormate = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.time = yearDate + '-' + month + '-' + dayFormate;
  dateObj.week = show_day[day];
  return dateObj;
}
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')

}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function send_photo(data, successfun) {
  var that = this
  for (let i = 0; i < data.length; i++) {
    console.log("data长度=" + data.length)
    console.log(data)
    wx.uploadFile({
      url: app.globalData.url + '/pub/jjr/reguser', //仅为示例，非真实的接口地址 自己写映射你Java接口的路径
      filePath: data[i] + "",
      name: 'file',
      success: function(res) {
        successfun(res)
      }
    })
  }
}
//横展开的提示，未定义样式，如需要可自行定义
function ts(res) {
  wx.showToast({
    title: res,
    duration: 2000,
    icon: 'none'
  });
}
module.exports = {
  // formatTime: formatTime,
  ts: ts,
  getDataRequest: getDataRequest,
  login: login,
  uploadimg: uploadimg,
  formatDate: formatDate,
  getDates: getDates,
  send_photo: send_photo,
  Encrypt: Encrypt,
  decrypt:decrypt

}
// }